/*
 * Util.java
 *
 * Copyright (c) 2010 Jaymie Strecker (strecker at cs.umd.edu). All rights reserved.
 *
 * This file is part of Tonic.
 *
 * Tonic is free software: you can redistribute it and/or modify
 * it under the terms of the GNU General Public License as published by
 * the Free Software Foundation, either version 3 of the License, or
 * (at your option) any later version.
 *
 * Tonic is distributed in the hope that it will be useful,
 * but WITHOUT ANY WARRANTY; without even the implied warranty of
 * MERCHANTABILITY or FITNESS FOR A PARTICULAR PURPOSE.  See the
 * GNU General Public License for more details.
 *
 * You should have received a copy of the GNU General Public License
 * along with Tonic.  If not, see <http://www.gnu.org/licenses/>.
 */

package tonic.audio;

import java.io.*;

/**
 *
 * @author Jaymie Strecker (strecker at cs.umd.edu)
 */
public class Util {

    /**
     * Returns the next lowest power of 2 (which is n if n is a power of 2)
     */
    protected static int previousPowerOf2(int n) {
        int prevLog = (int) Math.floor(log2((double) n));
        return (int) Math.pow(2, prevLog);
    }

    /**
     ** Returns the next highest power of 2 (which is n if n is a power of 2)
     */
    protected static int nextPowerOf2(int n) {
        int nextLog = (int) Math.ceil(log2((double) n));
        return (int) Math.pow(2, nextLog); 
    }

    /**
     * Returns true if n is an integer power of 2 (including 2^0).
     */
    protected static boolean isPowerOf2(int n) {
        int floorLog = (int) log2((double) n);
        return (int) Math.pow(2, floorLog) == n;
    }

    protected static double log2(double n) {
        return Math.log(n) / Math.log(2.0);
    }

    protected static float[] sineWave(Pitch pitch, int seconds, float samplesPerSecond) {
        return sineWave(pitch.frequency(0), seconds, samplesPerSecond);
    }

    protected static float[] sineWave(float frequency, int seconds, float samplesPerSecond) {
        int numSamples = (int) (seconds * samplesPerSecond);
        float[] wave = new float[numSamples];
        for (int i = 0; i < wave.length; i++) {
            float time = i / samplesPerSecond;
            wave[i] = (float) Math.sin(2 * Math.PI * frequency * time);
        }
        return wave;
    }

    protected static void arrayToFile(float[] a, String fileName) {
        try {
            File outFile = new File(fileName);
            FileWriter out = new FileWriter(outFile);
            for (int i = 0; i < a.length; i++) {
                out.write(a[i] + "\t");
            }
            out.write("\n");
            out.close(); 
        } catch (IOException e) {
            System.out.println("Couldn't write to file " + fileName);
        }
    }

}
